<template>
	<view class="box">
		<!-- <text @click="cliPause">{{ title }}</text>
		<button id="count" @click="count++">{{ count }}</button> -->

		<!-- 付费内容提示 -->
		<!-- <view class="pay-text" v-if="isShowPayText === 1 && AdBtnShow === false">
			该剧集为付费内容,完成支付即可观看~
		</view> -->

		<!-- 广告提示 -->
		<!-- <view v-if="isShowPayText === 1 && AdBtnShow" class="ad-tip-wrapper">
			<text>看完广告才能解锁本集</text>
			<text>拍摄不易，感谢您支持一下哦</text>
			<text
				v-if="IsStopAdTimeout === true"
				style="margin-top: 40rpx; font-size: 32rpx"
				>点击屏幕继续解锁剧集</text
			>
		</view> -->

		<!-- 广告点击区域 -->
		<!-- <view
			class="ad-thumb-wrapper"
			v-if="isShowPayText === 1 && AdBtnShow && IsStopAdTimeout"
			@click="AdTimeoutFunc"
		></view> -->

		<!-- 广告倒计时区域 -->
		<view
			class="ad-timeout-wrapper"
			v-if="isShowPayText === 1 && AdBtnShow && IsStopAdTimeout === false"
		>
			<view class="ad-timeout-btn" @click="handleAdClick"
				>{{ AdTimeoutNum }}s后看广告解锁剧集</view
			>
			<view class="ad-btn-close" @click="handleStopAdClick">×</view>
		</view>
	</view>
</template>
<!-- setRecommendConfig -->
<script>
import {
	getApiEpisodeList,
	dyGetEpisodeList,
	getApiVideoList,
	dyUnlockEpisode,
	getApiEpisodeInfo,
	getDyAdEpisodeInfo,
	RewardedVideoAdShow,
	RewardedVideoAdEnd,
	RewardedVideoAdNoEnd,
} from '@/api/teleplay'
import store from '@/store/index'
import { showMessage } from '@/utils/message'
const { getPlayletManager } = tt
let CacheEpisodeItem = uni.getStorageSync('episodeInfo')
// 导入工具函数
import { OSSImgUrl, isShowPay } from '@/utils'
export default {
	data() {
		return {
			pm: null,
			count: 0,
			title: 'Hello player click me pause',
			eid: '',
			IsUseAdPay: store.state.global.IsHasChannelType, // 是否使用广告支付
			currentSort: 0,
			currentAdSort: 0, // 当前广告倒计时剧集
			isShowPayText: null, // 付费内容文字
			AdBtnShow: false, // 是否显示广告按钮
			ttAdInstance: null, // 广告实例
			AdTimeoutNum: 3, // 广告倒计时秒数
			IsStopAdTimeout: false, // 是否暂停广告倒计时
			isAdLoading: false, // 广告是否正在加载中
			adTimer: null, // 广告倒计时计时器
			DyAdId: null, // 广告ID
			videoId: '', // 当前视频ID
		}
	},
	props: ['titles'],
	async beforeCreate() {
		// 初始化广告ID
		this.DyAdId = uni.getStorageSync('DyAdId') || null

		// 安全获取eid
		try {
			const userInfo = uni.getStorageSync('userInfo')
			this.eid = userInfo && userInfo.eid ? userInfo.eid : ''
		} catch (error) {
			console.warn('获取用户信息失败:', error)
			this.eid = ''
		}

		const pm = await getPlayletManager({
			is: 'playler', // 和插槽同名
		})
		this.pm = pm
		console.log(pm, this, 'player_pm_this_beforeCreate')
		pm.onPlay((e) => {
			console.error('触发开始播放onPlay回调:', e)
		})
		pm.onPause((e) => {
			console.log('触发暂停播放onPause回调:', e)
		})
		pm.onEnded(async (e) => {
			console.log('触发播放到末尾onEnded回调', e)
		})
		pm.onError((e) => {
			console.error('报错了 报错了', e)
		})

		pm.onWaiting((e) => {
			console.log('触发视频出现缓冲onWaiting回调:', e)
		})

		pm.onPlayBackRateChange((e) => {
			console.log('触发视频倍速改变onPlayBackRateChange回调:', e)
		})
		// 切换剧集
		pm.onChangeEpisode((e) => {
			console.log(
				'触发选集切换onChangeEpisode回调:',
				e,
				uni.getStorageSync('DyAdId'),
				'当前剧集:',
				this.currentSort,
				'广告剧集:',
				this.currentAdSort
			)
			this.getEpisodeInfo(e.seq)
			if (uni.getStorageSync('DyAdId')) {
				// 如果新剧集序号与当前剧集不同，则停止广告倒计时
				if (e.seq !== this.currentSort) {
					console.log('剧集已切换，停止当前广告倒计时', e.seq, this.currentSort)
					this.handleStopAdClick()
				}

				// 如果新剧集序号与正在解锁的广告剧集不同，且新剧集是unlock状态，则重置广告状态
				if (e.seq !== this.currentAdSort && e.status === 'unlock') {
					console.log(
						'切换到不需要解锁的新剧集，重置广告状态',
						e.seq,
						this.currentAdSort
					)
					this.AdBtnShow = false
					this.isShowPayText = null
					clearInterval(this.adTimer)
					this.adTimer = null

					// 重置loading状态
					if (this.isAdLoading) {
						this.isAdLoading = false
						uni.hideLoading()
					}

					// 尝试关闭正在展示的广告（如果可能）
					try {
						this.ttAdInstance &&
							this.ttAdInstance.destroy &&
							this.ttAdInstance.destroy()
						console.log('尝试销毁广告实例')
						setTimeout(() => {
							this.createAdInstance(this.DyAdId)
						}, 500)
					} catch (error) {
						console.error('尝试销毁广告实例失败:', error)
					}
				}

				// 当状态为lock时，启动广告倒计时
				if (e.status === 'lock') {
					this.currentSort = e.seq
					this.AdBtnShow = true
					this.isShowPayText = 1
					console.log('选集切换-需要广告解锁:', e)

					// 启动广告倒计时
					this.AdTimeoutFunc()
				}
				if (e.status === 'unlock') {
					this.AdBtnShow = false
					this.isShowPayText = null
					this.handleStopAdClick()
					console.log('销毁广告实例', this.ttAdInstance)
				}
			} else {
				// if (e.status === 'lock') {
				// 	pm.toggleCustomDialog()
				// }
				// const currentItem = uni
				// 	.getStorageSync('episodeList')
				// 	.find((item) => item.sort === e.seq)
				// // 从历史记录进来
				// if (e.scene === 'first_play' && currentItem.is_vip === 1) {
				// 	pm.toggleCustomDialog()
				// }
			}
		})
		pm.onLoadedMetaData((e) => {
			console.log(
				'触发视频元数据加载完成onLoadedMetaData回调:',
				e,
				uni.getStorageSync('episodeInfo')
			)
			this.$store.commit('teleplay/setEpisodeInfo', {
				...uni.getStorageSync('episodeInfo'),
				album_id: e.albumId,
				episode_id: e.episodeId,
				sort: e.seq,
			})
		})

		pm.onSeekComplete((e) => {
			console.log('触发seek完成onSeekComplete回调:', e)
		})

		pm.onMuteChange((e) => {
			console.log('触发静音状态改变onMuteChange回调:', e)
		})

		pm.onControlTap(async (e) => {
			const currentEpisodeInfo = uni.getStorageSync('episodeInfo') || {}
			console.log('触发点击控件onControlTap回调:', e, currentEpisodeInfo)

			if (e.controlType === 'subscribe') {
				const res = await saveApiUserCollect(
					currentEpisodeInfo.video_id,
					this.eid
				)
				if (res.code === 200) {
					uni.showToast({
						title: '追剧成功',
						icon: 'success',
					})
				}
			}
			if (e.controlType === 'unsubscribe') {
				const res = await delApiUserCollect(
					currentEpisodeInfo.video_id,
					this.eid
				)
				if (res.code === 200) {
					uni.showToast({
						title: '取消追剧成功',
						icon: 'success',
					})
				}
			}
		})
		pm.onOpenCatalog((e) => {
			console.log('触发点击选集onOpenCatalog回调:', e)
		})

		pm.onTapCustomIcon((e) => {
			console.log('触发点击自定义组件onTapCustomIcon回调:', e)
		})
		pm.onTapShare((e) => {
			console.log('onTapShare', e, CacheEpisodeItem)
			const launchData = uni.getLaunchOptionsSync()

			// 将参数转换成字符串携带分享在路径后
			const share_id = launchData.query.share_id
				? launchData.query.share_id
				: '3fbh0gcm03i517c772'
			return {
				// 分享数据
				title: CacheEpisodeItem.video_name,
				desc: CacheEpisodeItem.desc,
				path: `/pages/playlet/index?tt_album_id=${e.albumId}&tt_episode_id=${e.episodeId}`, // ?后面的参数会在转发页面打开时传入onLoad方法
				imageUrl: CacheEpisodeItem.img_url,

				templateId: share_id,
			}
		})
		pm.onShareSuccess((e) => {
			console.log('分享成功onShareSuccess回调:', e)
		})
		pm.onShareFail((e) => {
			console.log('分享失败onShareSuccess回调:', e)
		})
	},
	created() {
		console.log('playerCreated')

		// 如果有广告ID，创建广告实例
		if (this.DyAdId) {
			this.createAdInstance(this.DyAdId)
		}

		this.pm.onClickUnlock(async (e) => {
			console.log('点击解锁2', e)
			this.currentSort = e.seq

			this.getEpisodeInfo(e.seq, 'unlock')
		})
	},
	beforeMount() {
		console.log('playerBeforeMount')
	},
	mounted() {
		console.log('playerMounted')
	},
	beforeUpdate() {
		console.log('playerBeforeUpdate')
	},
	updated() {
		console.log('playerUpdated')
		this.count % 2 == 0
			? this.pm.setPlayStatus('play')
			: this.pm.setPlayStatus('pause')
	},
	beforeDestroy(e) {
		console.log('playerBeforeDestroy', e)
		// 在组件销毁前清除计时器
		if (this.adTimer) {
			clearInterval(this.adTimer)
			this.adTimer = null
		}
		uni.setStorageSync('recentVideo', {
			...uni.getStorageSync('episodeInfo'),
			// album_id: e.albumId,
			// episode_id: e.episodeId,
			// sort: e.seq,
		})
		// 销毁广告实例
		this.ttAdInstance?.destroy?.()
	},
	destroyed(e) {
		console.log('playerDestroyed', e)

		// 销毁广告实例
		if (this.ttAdInstance) {
			this.ttAdInstance.destroy()
			this.ttAdInstance = null
		}

		if (this.episodeInfo) {
			console.log('销毁页面', this.episodeInfo, this.currentSort)
			// uni.setStorageSync('recentVideo', {
			// 	...this.episodeInfo,
			// 	sort: this.currentSort,
			// })
		}
	},
	methods: {
		cliPause: function () {
			console.error(this.$props)
			this.pm.setPlayStatus('pause')
			this.$emit('cliPause', 1)
		},
		// 轮询获取eid的方法
		async getEid() {
			return new Promise((resolve) => {
				let count = 0
				const maxTries = 3
				const interval = 500 // 每次尝试间隔500ms

				const tryGetEid = () => {
					if (this.eid) {
						console.log('已获取到eid:', this.eid)
						resolve(this.eid)
						return
					}

					// 尝试从缓存中获取
					const userInfo = uni.getStorageSync('userInfo')
					if (userInfo && userInfo.eid) {
						this.eid = userInfo.eid
						console.log('从缓存获取到eid:', this.eid)
						resolve(this.eid)
						return
					}

					count++
					if (count >= maxTries) {
						console.warn('轮询获取eid失败，已达到最大尝试次数')
						resolve('') // 返回空字符串表示获取失败
						return
					}

					console.log(`尝试获取eid: 第${count}次，将在${interval}ms后重试`)
					setTimeout(tryGetEid, interval)
				}

				tryGetEid()
			})
		},
		async getEpisodeInfo(sort, type) {
			const DyAdId = uni.getStorageSync('DyAdId')
			this.currentSort = sort
			this.DyAdId = DyAdId
			console.log('🚀 获取剧集信息getEpisodeInfo:', sort, this.DyAdId)

			// 确保有eid值
			if (!this.eid) {
				console.log('eid不存在，开始轮询获取')
				this.eid = await this.getEid()
				if (!this.eid) {
					console.warn('轮询获取eid失败，可能影响后续操作')
				}
			}

			CacheEpisodeItem = uni.getStorageSync('episodeInfo') || {}
			const loadOption = uni.getStorageSync('loadOption') || {}
			// CacheEpisodeItem = this?.episodeList?.find((item) => item?.sort === sort)
			console.log('🚀 loadOption:', loadOption)
			// 优先使用传入的video_id，其次使用缓存中的
			const currentVideoId = loadOption.video_id || CacheEpisodeItem.video_id
			console.log('🚀 this.eid:', this.eid)
			try {
				const { data, code, msg } = await (this.DyAdId
					? getDyAdEpisodeInfo
					: getApiEpisodeInfo)(currentVideoId, sort, this.eid)

				if (msg === 'need_ad') {
					if (type === 'unlock') {
						// 立即看广告 没倒计时
						this.AdBtnShow = false
						this.isShowPayText = null

						this.handleAdClick()
					} else {
						// 看广告
						this.AdBtnShow = true
						this.isShowPayText = 1
						this.currentAdSort = sort

						console.log('🚀 ~ getEpisodeInfo ~ this.AdBtnShow:', this.AdBtnShow)
						this.AdTimeoutFunc() //广告倒计时
					}
					return new Promise((resolve, reject) => reject(new Error(msg)))
				}

				// 如果获取剧集失败跳转首页
				if (msg === 'invalid video_id') {
					showMessage('视频ID缺失, 请稍后重试~')
					setTimeout(() => {
						tt.switchTab({ url: '/pages/home/home' })
					}, 1000)
					return
				}
				// 如果剧集未上架弹窗提示
				if (code === 30006) {
					uni.showToast({
						title: '该视频未上架,可先观看其他剧集~',
						icon: 'none',
						duration: 1500,
					})
					// 获取剧集失败不播放视频
					this.episodeInfo.file_url = ''
					return new Promise((resolve, reject) => reject(new Error(msg)))
				}
				// 储存用户余额
				// 将VIP时间也重新赋值
				const { vip_time } = uni.getStorageSync('balance')
				uni.setStorageSync('balance', {
					balance: data.balance || 0,
					give_balance: data.give_balance || 0,
					vip_time: vip_time || 0,
				})

				// 储存过期时间
				const expire_time = data.expire_time - Date.now()
				// this.episodeInfo = Object.assign({}, this.episodeInfo, data)

				this.episodeInfo =
					this.episodeInfo && typeof this.episodeInfo === 'object'
						? { ...this.episodeInfo, ...(data || {}) }
						: data && typeof data === 'object'
						? { ...data }
						: {}
				uni.setStorageSync('episodeInfo', {
					...CacheEpisodeItem,
					...this.episodeInfo,
				})
				this.pm.setCurrentUnlock()
				// 视频过期重新发送请求
				if (expire_time !== 0 && this.flag) {
					this.flag = false
					this.timerId = setTimeout(async () => {
						const { data } = await (this.DyAdId
							? getDyAdEpisodeInfo
							: getApiEpisodeInfo)(currentVideoId, sort, this.eid)
						this.episodeInfo =
							this.episodeInfo && typeof this.episodeInfo === 'object'
								? { ...this.episodeInfo, ...(data || {}) }
								: data && typeof data === 'object'
								? { ...data }
								: {}
						this.flag = true
					}, expire_time)
				}
			} catch (error) {
				console.log('🚀 ~ getEpisodeInfo ~ error:', error)
				if (this.DyAdId) {
					// 需要广告支付的时候
					this.AdBtnShow = true
					this.isShowPayText = 1
					this.currentAdSort = sort
					this.AdTimeoutFunc() // 启动广告倒计时
				} else {
					const showPay = isShowPay(
						() => {
							// ios可以支付
							this.pm.toggleCustomDialog()

							// this.episodeInfo.file_url = ''
							// this.episodeInfo.sort = this.currentSort
							// 当余额不足时显示付费文字
							// if (error.message === 'not_balance') {
							// 	this.isShowPayText = 1
							// }
							new Promise((resolve, reject) => {
								reject(error)
							})
						},
						() => {
							// 跳转ios不许支付页面
							// 当余额不足时显示付费文字
							// if (error.message === 'not_balance') {
							// 	this.isShowPayText = 1
							// }
							// 如果不是从ios不能支付页面跳转就跳转页面
							if (!this.iosPage) {
								uni.navigateTo({
									url: `/pages/playlet/index?seq=${sort}&tt_album_id=${this.episodeInfo.album_id}&tt_episode_id=1&is_continue=1`,
								})
							}
							this.iosPage = false
						}
					)

					if (!showPay) {
						this.showModal = true
						this.currentIndex = this.currentIndex - 1
						// this.sort = this.sort - 1
						// this.getEpisodeInfo(this.sort, this.episodeInfo.video_id)
						return
					}
				}
			}
		},
		// 停止广告倒计时
		handleStopAdClick() {
			this.IsStopAdTimeout = true // 暂停倒计时
			this.AdBtnShow = false
			clearInterval(this.adTimer)
			this.adTimer = null
		},

		// 广告倒计时函数
		AdTimeoutFunc() {
			clearInterval(this.adTimer)
			this.AdTimeoutNum = 3
			this.IsStopAdTimeout = false

			this.adTimer = setInterval(() => {
				this.AdTimeoutNum -= 1
				if (this.AdTimeoutNum <= 0) {
					clearInterval(this.adTimer)
					this.adTimer = null
					this.handleAdClick() // 自动触发广告播放
				}
			}, 1000)
		},

		// 广告相关方法
		createAdInstance(adUnitId) {
			if (!adUnitId) return false

			this.ttAdInstance = tt.createRewardedVideoAd({
				adUnitId: adUnitId,
			})

			// 监听错误
			this.ttAdInstance.onError((err) => {
				console.log('广告加载错误', err)
				uni.hideLoading()
				this.isAdLoading = false

				uni.showToast({
					title: '广告加载失败，稍后再试',
					icon: 'none',
					duration: 1500,
					mask: true,
				})
			})

			// 监听视频播放完成
			this.ttAdInstance.onClose(async (data) => {
				console.log(
					'广告关闭',
					data,
					'当前剧集:',
					this.currentSort,
					'广告剧集:',
					this.currentAdSort
				)
				uni.hideLoading()
				this.isAdLoading = false

				// 检查当前剧集与广告剧集是否相同
				const isSameEpisode = this.currentSort === this.currentAdSort
				console.log('广告关闭时检查剧集:', isSameEpisode ? '相同' : '不同')

				if (data.isEnded) {
					console.log('观看了', data.count, '个视频')

					// 埋点：广告观看完成
					RewardedVideoAdEnd({
						channel_id: uni.getStorageSync('channel_id'),
						plan_id: uni.getStorageSync('plan_id'),
						eid: this.eid,
					}).catch((err) => {
						console.log('埋点失败', err)
					})

					// 解锁当前剧集
					try {
						// 查找当前剧集对应的项
						const currentItem = uni
							.getStorageSync('episodeList')
							.find(
								(item) =>
									item.sort ===
									(isSameEpisode ? this.currentSort : this.currentAdSort)
							)

						// 匹配自定义播放器的做法：优先使用剧集项的video_id，其次使用剧集信息中的
						const currentVideoId = Number(
							CacheEpisodeItem?.video_id || this.videoId
						)

						// 使用广告剧集或当前剧集（如果相同）
						const currentSort = isSameEpisode
							? this.currentSort
							: this.currentAdSort
						const encrypted = currentItem?.encrypted

						console.log(
							'广告解锁 - 视频ID:',
							currentVideoId,
							'剧集:',
							currentSort,
							'encrypted:',
							encrypted
						)

						const res = await dyUnlockEpisode({
							video_id: currentVideoId,
							sort: currentSort,
							eid: this.eid,
							channel_id: uni.getStorageSync('channel_id'),
							plan_id: uni.getStorageSync('plan_id'),
							encrypted: encrypted,
						})

						if (res?.code == 200) {
							console.log('广告观看完毕解锁成功', res)
							// 使用抖音API解锁当前剧集
							if (isSameEpisode) {
								// 剧集没有变化，直接解锁当前
								this.pm.setCurrentUnlock()
								this.AdBtnShow = false
								this.isShowPayText = null
							} else {
								// 剧集已经变化，尝试解锁原剧集
								console.log(
									'广告期间剧集已切换，尝试解锁原剧集:',
									this.currentAdSort
								)
								this.pm.setEpisodeUnlock &&
									this.pm.setEpisodeUnlock(this.currentAdSort)

								// 如果当前新剧集也需要解锁，可以在这里处理
							}
						}
					} catch (error) {
						console.error('解锁失败', error)
					}
				} else {
					uni.showToast({
						title: '未观看完视频',
						icon: 'none',
						duration: 1500,
						mask: true,
					})
					console.log(
						'未观看完视频',
						this.currentAdSort,
						this.currentSort,
						this.currentAdSort === this.currentSort
					)

					// 只有当前剧集与广告剧集相同时，才重启倒计时
					if (this.currentAdSort === this.currentSort) {
						// 重新启动倒计时
						this.AdTimeoutFunc()
					}

					// 埋点：广告未看完
					RewardedVideoAdNoEnd({
						channel_id: uni.getStorageSync('channel_id'),
						plan_id: uni.getStorageSync('plan_id'),
						eid: this.eid,
					}).catch((err) => {
						console.log('埋点失败', err)
					})
				}
			})

			// 预加载广告资源
			this.ttAdInstance.load()
			return true
		},

		// 点击解锁广告按钮
		handleAdClick() {
			if (this.isAdLoading) return
			this.isAdLoading = true

			// 重要：记录当前要解锁的剧集编号
			this.currentAdSort = this.currentSort
			console.log('启动广告，当前要解锁的剧集:', this.currentAdSort)

			uni.showLoading({
				title: '加载中',
				mask: true,
			})
			console.log('点击解锁广告按钮', this.DyAdId)
			// 确保广告实例已创建
			if (!this.ttAdInstance && !this.createAdInstance(this.DyAdId)) {
				uni.hideLoading()
				this.isAdLoading = false

				uni.showToast({
					title: '广告加载失败，请稍后再试',
					icon: 'none',
					duration: 1500,
				})
				return
			}

			// 清除计时器
			clearInterval(this.adTimer)
			this.adTimer = null

			// 显示广告
			this.ttAdInstance
				.show()
				.then(() => {
					console.log('显示广告成功')

					// 埋点：广告展示
					RewardedVideoAdShow({
						channel_id: uni.getStorageSync('channel_id'),
						plan_id: uni.getStorageSync('plan_id'),
						eid: this.eid,
					}).catch((err) => {
						console.log('埋点失败', err)
					})
				})
				.catch((err) => {
					console.log('广告加载失败', err)
					uni.hideLoading()
					this.isAdLoading = false

					uni.showToast({
						title: '广告加载失败，请稍后再试',
						icon: 'none',
						duration: 1500,
					})
				})
		},
	},
}
</script>

<style>
.box {
	color: orange;
	/* position: relative; */
}

.ad-tip-wrapper {
	/* position: absolute;
	top: 40%;
	left: 50%; */
	transform: translate(-50%, -50%);
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
	background: rgba(0, 0, 0, 0.5);
	border-radius: 30%;
}

.ad-tip-wrapper text {
	color: #fff;
	font-size: 30rpx;
	white-space: nowrap;
}

.ad-tip-wrapper text:first-child {
	margin-bottom: 10rpx;
}

.ad-thumb-wrapper {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 50;
}

.ad-timeout-wrapper {
	position: absolute;
	bottom: 190rpx;
	/* right: 10rpx; */
	display: inline-flex;
	justify-content: space-between;
}

.ad-timeout-btn {
	border-radius: 12rpx;
	box-sizing: border-box;
	padding: 15rpx 20rpx;
	font-size: 28rpx;
	color: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	background: linear-gradient(to bottom, #ffc9a0, #fd832c, #fe6b01);
}

.ad-btn-close {
	color: #fff;
	background-color: #746c68;
	font-weight: bold;
	margin-left: 10rpx;
	border-radius: 12rpx;
	box-sizing: border-box;
	padding: 6rpx 16rpx;
	font-size: 44rpx;
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.pay-text {
	width: 85%;
	position: absolute;
	top: 40%;
	left: 47%;
	transform: translate(-41%, -50%);
	font-size: 34rpx;
	color: #fff;
}
</style>
